package com.heima.article.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.heima.article.constants.ArticleConstants;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;

import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult load(ArticleHomeDto dto) {
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, ArticleConstants.LOADTYPE_LOAD_MORE);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadmore(ArticleHomeDto dto) {
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, ArticleConstants.LOADTYPE_LOAD_MORE);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadnew(ArticleHomeDto dto) {
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, ArticleConstants.LOADTYPE_LOAD_NEW);
        return ResponseResult.okResult(apArticles);
    }

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private FreemarkerGenerator freemarkerGenerator;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;


    @Override
    @Async
    //自动上传生成静态文件
    public void createStaticUrl(Long articleId) {
        //1.根据articleId查询文章内容
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId, articleId);
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(wrapper);
        if (apArticleContent == null) {
            log.info("文章不存在!");
            return;
        }
        //2.将查询到的内容封装到map集合中
        Map<String, Object> map = new HashMap<>();
        map.put("content", JSON.parseArray(apArticleContent.getContent()));

        //3.调用freemaker插件 生成html文件
        InputStream is = freemarkerGenerator.generate("article.ftl", map);

        //4.调用minio插件 实现文件上传
        String url = minIoTemplate.uploadFile("", articleId + ".html", is, "html");
        //5.更新article表中的url字段
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle == null) {
            log.warn("文章为空");
            return;
        }
        apArticle.setStaticUrl(url);
        apArticleMapper.updateById(apArticle);
    }

    @Override
    @Transactional
    //保存文章到app端数据库
    public ResponseResult saveArticle(ArticleDto dto) {
        //判断dto中是否有id
        Long id = dto.getId();
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        //没有id,新增流程
        if (id == null) {
            //新增article表

            int articleresult = apArticleMapper.insert(apArticle);
            if (articleresult < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
            }
            //新增config表
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsDelete(false);
            apArticleConfig.setIsDown(false);
            apArticleConfig.setIsForward(true);
            int configResult = apArticleConfigMapper.insert(apArticleConfig);
            if (configResult < 1) {
                log.warn("config表新增失败");
                throw new RuntimeException("config表新增失败");
            }
            //新增content表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            int contentResult = apArticleContentMapper.insert(apArticleContent);
            if (contentResult < 1) {
                log.warn("content表新增失败");
                throw new RuntimeException("content表新增失败");
            }
            //生成静态文件
            createStaticUrl(apArticle.getId());
            return ResponseResult.okResult(apArticle.getId());
        } else {
            int i = apArticleMapper.updateById(apArticle);
            if (i < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
            }
            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId, id);

            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setContent(dto.getContent());
            int update = apArticleContentMapper.update(articleContent, wrapper);
            if (update < 1) {
                log.warn("content表修改失败");
                throw new RuntimeException("content表修改失败");
            }
            //生成静态文件
            createStaticUrl(id);
            return ResponseResult.okResult(id);
        }

    }
}
